/********************************************************************************
 * Copyright(c) 2020-2025 BST All rights reserved.
 * - Filename
 * - Author
 * - Version V1.0.0
 * - Date    2025/08/05
 * - Brief
 * - FunctionList:
 ******************************************************************************
 * History:
 *
 *
 *
 ******************************************************************************
 */
#include "ImageSender.hpp"

#include <fstream>
#include <iostream>

#include "CommonUtil.hpp"
#include "ConfigSingleton.hpp"
#include "hv/base64.h"

ImageSender::ImageSender(void *context) {
  _context = (vzmq::VzmqContext *)context;
}
ImageSender::~ImageSender() {}
void ImageSender::start(const std::string &path) {
  _isExit = false;
  _reader = std::make_shared<FileReader>(ConfigSingleton::get().getReplayType(),
                                         path);
  _fileList = _reader->getFileInfoList();
  std::cout << "TotalFileCount:" << _fileList.size() << std::endl;
  _imgFameDispatch =
      _context->createPublisher<ImageFrame>(REPLAY_IMAGE_FRAME_CHANNAL_PUB);
  this->_thread.reset(new std::thread(std::bind(&ImageSender::loop, this)));
}
void ImageSender::stop() {
  _isExit = true;
  if (_thread != nullptr && _thread->joinable()) {
    _thread->join();
  }
}
void ImageSender::loop() {
  while (!_isExit) {
    for (auto [key, val] : _fileList) {
      if (_isExit) break;
      auto frame = std::make_shared<ImageFrame>();
      frame->set_seq(key);
      frame->set_image_type(JPEG);
      frame->set_height(val.height);
      frame->set_width(val.width);
      frame->set_timestamp(val.timestamp);
      frame->set_image_name(val.imageName);
      std::ifstream file(val.fileName, std::ios::binary | std::ios::ate);
      if (!file.is_open()) {
        std::cerr << "无法打开文件: " << val.fileName << std::endl;
        continue;
      }
      std::streamsize size = file.tellg();
      file.seekg(0, std::ios::beg);
      std::vector<unsigned char> buffer(size);
      if (!file.read(reinterpret_cast<char *>(buffer.data()), size)) {
        std::cerr << "读取文件失败" << std::endl;
        continue;
      }
      auto imageBase64 = hv::Base64Encode(
          reinterpret_cast<const uint8_t *>(buffer.data()), buffer.size());
      frame->set_data(imageBase64);
      _imgFameDispatch->publish(std::move(frame));
      std::this_thread::sleep_for(
          std::chrono::milliseconds(ConfigSingleton::get().getSendPeriod()));
    }
    if (_isExit) break;
    {}
  }
}
